package pers.dzk.myplayer;

import org.bytedeco.javacv.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
/**
 * @author 丁泽凯
 * 这个类的代码是我抄的只会用QAQ
 */
public class Factory {
    private static void videoToMusic(String videoPath){
        System.out.println("提取音频文件");
        File file=new File(videoPath);
        //抓取资源
        FFmpegFrameGrabber frameGrabber1 = new FFmpegFrameGrabber(file);
        Frame frame;
        FFmpegFrameRecorder recorder;
        String fileName;
        try{
            frameGrabber1.start();
            fileName = "music/"+file.getName().split("\\.")[0]+".wav";
            System.out.println("--文件名-->>"+fileName);
            recorder = new FFmpegFrameRecorder(fileName,frameGrabber1.getAudioChannels());
            recorder.setFormat("wav");
            recorder.setSampleRate(frameGrabber1.getSampleRate());
            recorder.setTimestamp(frameGrabber1.getTimestamp());
            recorder.setAudioQuality(0);
            recorder.start();
            int index=0;
            while (true){
                frame=frameGrabber1.grab();
                if(frame==null){
                    System.out.println("视频处理完成");
                    break;
                }
                if(frame.samples!=null){
                    recorder.recordSamples(frame.sampleRate,frame.audioChannels,frame.samples);
                }
                System.out.println("帧值="+index);
                index++;
            }
            recorder.stop();
            recorder.release();
            frameGrabber1.stop();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String[][] getString(File root) {
        try {
            String[][] strings;
            int len = root.listFiles().length;
            String root2 = root.getPath()+"/";
            File[] files = new File[len];
            for (int i = 0; i < len ;i++) {
                files[i] = new File(root2+(i+1)+".txt");
            }
            FileInputStream fis = new FileInputStream(files[0]);
            BufferedInputStream bis = new BufferedInputStream(fis);
            InputStreamReader isr = new InputStreamReader(bis);
            BufferedReader br = new BufferedReader(isr);
            int len2 = 0;
            while ( br.readLine() != null){
                len2++;
            }
            br.close();
            strings = new String[files.length][len2];
            for (int i = 0;i < files.length;i++){
                fis = new FileInputStream(files[i]);
                bis = new BufferedInputStream(fis);
                isr = new InputStreamReader(bis);
                br = new BufferedReader(isr);
                String s;
                int j = 0;
                while ((s = br.readLine()) != null){
                    strings[i][j++] = s;
                }
                br.close();
            }
            return strings;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static void videoToImageToString(File video){
        videoToMusic(video.getPath());
        String name = getName(video);
        String[] imagePath = videoToImage(video);
        for (String path : imagePath){
            imageToString(path,name);
        }
    }
    public static int getFrameRate(File video){
        try (FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video)){
            ff.start();
            return (int)ff.getFrameRate();
        } catch (FrameGrabber.Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static String getName(File file){
        return file.getName().split("\\.")[0];
    }
    private static void saveVideo(File video) throws IOException {
        File video2 = new File("video/"+video.getName());
        if(video2.createNewFile()){
            FileInputStream is = new FileInputStream(video);
            BufferedInputStream bis = new BufferedInputStream(is);
            FileOutputStream fos = new FileOutputStream(video2);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte[] data = new byte[1024];
            while (bis.read(data) != -1) {
                bos.write(data);
            }
            bis.close();
            bos.close();
        }
    }
    /**
     * 根据读取到的视频文件，获取视频中的每一帧图片
     * @param video 视频文件
     */
    private static String[] videoToImage(File video){
        try {
            saveVideo(video);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //1.根据一个视频文件，创建一个按照视频中每一帧进行抓取图片的抓取对象
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        String[] imagePath = null;
        String name = video.getName().split("\\.")[0];
        String root = "img/"+name+"/";
        File file = new File(root);
        file.mkdir();
        try {
            ff.start();
            //抓每一帧图片
            //2.先知道这个视频一共有多少帧
            int length = ff.getLengthInFrames();
            imagePath = new String[length];
            System.out.println("图片数量"+length);
            System.out.println("视频帧率"+ff.getFrameRate());
            System.out.println("視頻高度"+ff.getImageHeight());
            System.out.println("視頻寬度"+ff.getImageWidth());
            //3.读取视频中每一帧图片
            Frame frame;
            for(int i=1;i<length;i++){
                frame = ff.grabFrame();
                if(frame.image == null){
                    i--;
                    continue;
                }
                //将获取的帧，存储为图片//创建一个帧-->图片的转换器
                Java2DFrameConverter converter = new Java2DFrameConverter();
                //转换
                BufferedImage image = converter.getBufferedImage(frame);
                String imgPath = root+i+".png";
                File picFile = new File(imgPath);
                //将图片保存到目标文件中
                ImageIO.write(image, "png", picFile);
                imagePath[i] = imgPath;
                System.out.println("生成圖片: "+picFile.getCanonicalPath());
            }
            ff.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imagePath;
    }
    /**
     * 生成字符串画
     * @param imgPath 图片路径
     * @throws IOException
     */
    private static void imageToString(String imgPath,String name) {
        String root = "txt/"+name+"/";
        new File(root).mkdir();
        try {
            String img="";
            File file = new File(imgPath);
            BufferedImage binaryBufferedImage = ImageIO.read(file);
            int orgWidth=binaryBufferedImage.getWidth();
            int orgHeight=binaryBufferedImage.getHeight();
            int size=Math.max(orgHeight,orgWidth);
            int w = size>1000?binaryBufferedImage.getWidth()/12:orgWidth;
            int h = size>1000?binaryBufferedImage.getHeight()/12:orgHeight;
            binaryBufferedImage.getGraphics().drawImage(binaryBufferedImage, 0, 0, w, h, null);
            // 字符串由复杂到简单,备选 %%*o!;.
            final String base = "%*o!;.";
            for (int y = 0; y < h; y += 2) {
                for (int x = 0; x < w; x++) {
                    final int pixel = binaryBufferedImage.getRGB(x, y);
                    final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
                    final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
                    final int index = Math.round(gray * (base.length() + 1) / 255);
                    img += (index >= base.length() ? " " : String.valueOf(base.charAt(index)));
                }
                img += "\n";
            }
            String txtPath = file.getName().split("\\.")[0]+".txt";
            File file2 = new File(root+txtPath);

            file2.createNewFile();
            System.out.println("生成String: "+file2.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(file2);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            PrintWriter pw = new PrintWriter(osw);
            pw.println(img);
            pw.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
